<template>
    <div>
        <div>
            <el-row>
                <!-- <el-col
                    ref="layoutTemplate"
                    :span="5"
                    v-show="isMyOpinionTab"
                >
                    <el-tabs
                        v-model="diagnosisTemplateTabActive"
                        @tab-click="diagnosisTemplateTabChange"
                    >
                        <el-tab-pane
                            label="机构模板"
                            name="orgTemplate"
                            style="padding-top: 10px"
                        >
                        </el-tab-pane>
                        <el-tab-pane
                            label="我的模板"
                            name="myTemplate"
                            style="padding-top: 10px"
                        >
                        </el-tab-pane>
                    </el-tabs>
                    <el-row>
                        <el-input
                            v-model="diagnosisTemplateFilterKey"
                            placeholder="请输入关键字"
                            class="input-form"
                            size="mini"
                        >
                        </el-input>
                        <el-button
                            @click="diagnosisTemplateFilter"
                            size="mini"
                            class="button-list-item"
                        >
                            过滤
                        </el-button>
                    </el-row>
                    <el-tree
                        node-key="id"
                        v-loading="!isDiagnosisTemplateReady"
                        :data="diagnosisTemplateList"
                        :props="diagnosisTemplateProps"
                        :load="diagnosisTemplateLoad"
                        :default-expanded-keys="diagnosisExpandList"
                        accordion
                        lazy
                    >
                        <span
                            slot-scope="{ node, data }"
                            class="diagnosis-template-tree"
                        >
                            <span class="diagnosis-template-tree-message">
                                <el-button
                                    @click="diagnosisTemplateNodeClick(data, node)"
                                    size="mini"
                                    type="text"
                                    style="color: #000"
                                >
                                    {{ node.label }}
                                </el-button>
                                <el-button
                                    v-if="diagnosisTemplateTabActive === 'orgTemplate'"
                                    @click="diagnosisTemplateNodeCopy(node)"
                                    size="mini"
                                    type="text"
                                >
                                    复制
                                </el-button>
                            </span>
                        </span>
                    </el-tree>
                </el-col> -->
                <el-col
                    :span="18"
                    :offset="1"
                >
                    <!--<el-row
                        v-if="!isFinished"
                        style="height: 40px"
                        type="flex"
                        align="middle"
                    >
                         <el-button
                            @click="inviteDialogOpen"
                            :disabled="
                !(tabActiveUserId == primaryDoctor.expertId && tabActiveUserId == user.id) ||
                (tabActiveUserId == user.id && thisOpinion.isFinished == 1)
              "
                            class="button-list-item"
                            type="primary"
                            size="mini"
                        >
                            邀请专家
                        </el-button>
                        <el-button
                            @click="consultationSave"
                            :disabled="
                (!isMyOpinionTab && true) ||
                tabActiveUserId != user.id ||
                (tabActiveUserId == user.id && thisOpinion.isFinished == 1)
              "
                            class="button-list-item"
                            type="primary"
                            size="mini"
                        >
                            暂存
                        </el-button>
                        <el-button
                            @click="consultationIssue"
                            :disabled="
                !isPrimarySpecialist ||
                tabActiveUserId != user.id ||
                (tabActiveUserId == user.id && thisOpinion.isFinished == 1)
              "
                            class="button-list-item"
                            type="primary"
                            size="mini"
                        >
                            发布
                        </el-button>
                        <el-button
                            @click="shareQRcode"
                            class="button-list-item"
                            type="primary"
                            size="mini"
                        >
                            分享二维码
                        </el-button> -->
                    <!-- <el-button
              :disabled="!isPrimarySpecialist&&opinionTabActive!=user.id"
              class="button-list-item"
              type="primary"
              size="mini"
            >
              转终审
            </el-button> -->
                    <!-- <el-button
                            @click="consultationSendBack"
                            :disabled="
                !isPrimarySpecialist ||
                tabActiveUserId != user.id ||
                (tabActiveUserId == user.id && thisOpinion.isFinished == 1)
              "
                            class="button-list-item"
                            size="mini"
                        >
                            退回
                        </el-button>
                        <el-button
                            @click="goBack"
                            class="button-list-item"
                            size="mini"
                        > 返回 </el-button>
                        <el-button
                            class="button-list-item"
                            @click="addStaining"
                            :disabled="
                tabActiveUserId != user.id ||
                (tabActiveUserId == user.id && thisOpinion.isFinished == 1)
              "
                            size="mini"
                        >
                            +特殊染色
                        </el-button>
                        <el-button
                            class="button-list-item"
                            @click="addMolecular"
                            :disabled="
                tabActiveUserId != user.id ||
                (tabActiveUserId == user.id && thisOpinion.isFinished == 1)
              "
                            size="mini"
                        >
                            +分子病理
                        </el-button>
                        <el-button
                            @click="addInc"
                            :disabled="
                tabActiveUserId != user.id ||
                (tabActiveUserId == user.id && thisOpinion.isFinished == 1)
              "
                            class="button-list-item"
                            size="mini"
                        >
                            +免疫组化
                        </el-button> 
                    </el-row> -->
                    <!-- <el-row
                        v-else
                        style="height: 40px"
                        type="flex"
                        align="middle"
                    >
                        <el-button
                            @click="consultationSave"
                            :disabled="!isMyOpinionTab && true"
                            class="button-list-item"
                            type="primary"
                            size="mini"
                        >
                            暂存
                        </el-button>
                        <el-button
                            @click="consultationRecycle"
                            v-show="!thisOpinion.isFinal == 1"
                            :disabled="
                !isPrimarySpecialist || tabActiveUserId != user.id || orders.serviceStatus == 2
              "
                            class="button-list-item"
                            type="primary"
                            size="mini"
                        >
                            回收报告
                        </el-button>
                        <el-button
                            @click="reportViewClick"
                            class="button-list-item"
                            size="mini"
                        >
                            报告预览
                        </el-button>

                        <el-button
                            :disabled="
                (thisOpinion && !thisOpinion.isFinished == 1) ||
                isCopy ||
                tabActiveUserId == user.id
              "
                            class="button-list-item"
                            size="mini"
                            @click="copyClick()"
                        >
                            复制（{{ thisOpinion.expertName }}）
                        </el-button>
                    </el-row> -->

                    <el-tabs
                        v-model="opinionTabActive"
                        @tab-click="opinionTabChange"
                        type="card"
                        style="margin-top: 10px"
                    >
                        <el-tab-pane
                            v-for="tab in opinionTabList"
                            :name="tab.key"
                            :label="tab.label"
                            :key="tab.key"
                        >
                        </el-tab-pane>
                    </el-tabs>

                    <div v-if="isDispatched">
                        <el-row
                            class="line-text"
                            type="flex"
                            justify="space-between"
                            style="margin-top: 10px"
                        >
                            <span class="content-text">病理诊断：</span>
                        </el-row>
                        <el-row style="margin-top: 10px">
                            <el-input
                                :readonly="!isMyOpinionTab || isFinishedOfMyDiagnosis"
                                v-model="opinionCurrent.input_binglizhenduan"
                                placeholder="请书写病理诊断"
                                :rows="10"
                                type="textarea"
                            >
                            </el-input>
                        </el-row>
                        <el-row
                            class="line-text"
                            type="flex"
                            justify="space-between"
                            style="margin-top: 10px"
                        >
                            <span class="content-text">建议及解释：</span>
                        </el-row>
                        <el-row style="margin-top: 10px">
                            <el-input
                                :readonly="!isMyOpinionTab || isFinishedOfMyDiagnosis"
                                v-model="opinionCurrent.input_jujian"
                                placeholder="请书写相关建议及解释的内容"
                                :rows="10"
                                type="textarea"
                            >
                            </el-input>
                        </el-row>
                        <el-row
                            class="line-text"
                            type="flex"
                            justify="space-between"
                            style="margin-top: 10px"
                        >
                            <span class="content-text">加做项目：</span>
                        </el-row>
                        <el-row style="margin-top: 10px">
                            <el-input
                                :readonly="!isMyOpinionTab || isFinishedOfMyDiagnosis"
                                v-model="opinionCurrent.input_extroProject"
                                placeholder="请书写相关加做项目的内容"
                                :rows="2"
                                type="textarea"
                            >
                            </el-input>
                        </el-row>
                    </div>
                    <div v-else>
                        <span>未分配</span>
                    </div>
                </el-col>
            </el-row>

            <el-dialog
                title="邀请专家"
                :visible.sync="inviteDialog.visible"
                :close-on-click-modal="false"
                :modal-append-to-body="false"
                append-to-body
                width="60%"
            >
                <base-table
                    ref="inviteTable"
                    v-loading="!inviteTable.isReady"
                    :data="inviteTable.data"
                    :header="inviteTable.header"
                    :operation="inviteTable.operation"
                    :pageInfo="inviteTable.pageInfo"
                    :selected="true"
                    :pageSizes="[5, 10, 15]"
                    @selectedRow="inviteTableSelectedRow"
                    @pageJumpTo="inviteTablePageJumpTo"
                    @sizeChange="inviteTableSizeChange"
                >
                </base-table>
                <span
                    slot="footer"
                    class="dialog-footer"
                    style="text-align: right"
                >
                    <el-button
                        @click="inviteDialog.visible = false"
                        size="mini"
                    >关闭</el-button>
                    <el-button
                        @click="inviteSpecialist"
                        size="mini"
                        type="primary"
                    >邀请</el-button>
                </span>
            </el-dialog>
        </div>
        <div>
            <ConsultationPlus
                v-if="thisOpinion && thisOpinion.expertId"
                :orderId="orders.id"
                :diagnosisId="opinionTabActiveId"
                :orders="orders"
                ref="consultationPlus"
                @addPlus="addPlus"
            >
            </ConsultationPlus>
        </div>
        <el-dialog
            title="分享二维码"
            :visible.sync="shareDialogVisible"
            width="30%"
        >
            <div>{{shareName}}医生邀请您参与这个病人的会诊</div>
            <div class="qrcode-box">
                <vue-qr
                    :logo-src="logoSrc"
                    :size="140"
                    :margin="0"
                    :auto-color="true"
                    :dot-scale="1"
                    :text="appSrc"
                />
            </div>

        </el-dialog>
    </div>
</template>

<script>
import ConsultationDefault from '@/templates/ConsultationDefault'
import BaseTable from '@/templates/components/BaseTable'
import ConsultationPlus from '@/templates/components/ConsultationPlus'
import moment from 'moment'
import _ from 'lodash'
import VueQr from 'vue-qr'
const Qs = require('qs')

const opinionDataBase = {
  diagnosis: '',
  situation: ''
}

export default {
  name: 'ConsultationOpinion',
  components: {
    BaseTable,
    ConsultationPlus,
    VueQr
  },
  props: {
    orders: {
      type: Object,
      default: ConsultationDefault
    }
  },
  data() {
    return {
      shareName: this.$store.state.user.name,
      logoSrc: '',
      appSrc: '', //二维码包含的url字符串
      shareDialogVisible: false,
      extraProjectList: [], //点击医生时筛选出此医生所推荐的加做项目
      tabActiveUserId: 0,
      isThereAFinalReview: null, //0是无终审，1是有终审
      uArgs: this.$store.getters.getUArgs,
      user: this.$store.getters.getUser,
      // layoutTemplate 相关
      diagnosisTemplateTabActive: 'orgTemplate',

      isDiagnosisTemplateReady: false,
      diagnosisTemplateFilterKey: '',
      diagnosisTemplateList: [],
      diagnosisTemplateProps: {
        children: 'children',
        label: 'nodeName',
        isLeaf: 'isLeaf'
      },
      diagnosisExpandList: [],

      opinionTabList: [],
      opinionTabActive: '',

      opinionCurrent: {
        input_binglizhenduan: '',
        input_jujian: '',
        input_extroProject: ''
      },

      inviteDialog: {
        visible: false
      },
      typeMap: {
        1: '特殊染色',
        2: '分子病理',
        3: '免疫组化'
      },
      inviteTable: {
        isReady: false,
        data: [],
        header: [
          {
            prop: 'name',
            label: '姓名',
            width: '100'
          },
          {
            prop: 'genderName',
            label: '性别',
            width: '55'
          },
          {
            prop: 'jobNumber',
            label: '工号',
            width: '120'
          },
          {
            prop: 'positionName',
            label: '职级',
            width: '60'
          },
          {
            prop: 'medicalTitleName',
            label: '职称',
            width: '60'
          },
          {
            prop: 'createTime',
            label: '注册时间',
            width: '160'
          },
          {
            prop: 'area',
            label: '所在地'
          },
          {
            prop: 'statusName',
            label: '用户状态',
            width: '100'
          }
        ],
        operation: [],
        pageInfo: {
          page: 1,
          size: 15,
          total: 0
        }
      },
      opinionTabActiveId: '',
      inviteSelected: new Set()
    }
  },
  computed: {
    diagnosisTemplatesType() {
      return this.diagnosisTemplateTabActive === 'orgTemplate' ? 1 : 2
    },
    currentLevel() {
      return _.get(this.orders, 'currentLevel', -1)
    },
    isDispatched() {
      return this.orders.serviceStatus > 0
    },
    opinionList() {
      const detailList = this.orders.patients[0].expertDiagnosis
      return detailList === null ? [] : detailList
    },
    thisOpinion() {
      return this.opinionList.find(t => t.id === parseInt(this.opinionTabActive, 10))
    },
    isCopy() {
      return !(
        this.opinionTabList.some(n => n.expertId === this.user.id) &&
        this.opinionList.filter(n => n.expertId === this.user.id).some(n => !n.isFinished)
      )
    },
    isFinished() {
      if (!this.thisOpinion) {
        return false
      }
      return this.thisOpinion.isFinished == 1
    },
    isFinishedOfMyDiagnosis() {
      return _.get(this.thisOpinion, 'isFinished', 0) == 1
    },

    primaryDoctor() {
      return this.opinionList.find(t => t.type == 0)
    },
    primaryOpinion() {
      return this.opinionList.find(t => t.expertId == this.user.id)
    },

    isPrimarySpecialist() {
      return this.user.id === _.get(this.primaryOpinion, 'expertId', 0)
    },
    isMyOpinionTab() {
      let _this = this
      if (this.isFinished == 1 && this.isPrimarySpecialist) return false
      if (
        _this.orders.patients.length == 0 ||
        _this.orders.patients[0].expertDiagnosis.length == 0
      ) {
        return false
      }
      return _this.orders.patients[0].expertDiagnosis.some(
        item => item.id == this.opinionTabActive && item.expertId == _this.user.id
      )
    }
  },
  mounted() {
    // 诊断模板获取
    //this.diagnosisTemplateRequest()
    this.opinionTabListInit()
  },
  methods: {
    shareQRcode() {
      this.shareDialogVisible = true
      this.appSrc = ''
    },
    addPlus(arr) {
      let arrText = ''
      arr.forEach(item => {
        item.result = item.result ? item.result : item.resultUrl ? '结果已上传' : '暂未录入结果'
        arrText += item.doctorAdviceName + ':' + item.result + ';'
      })
      this.opinionCurrent.input_extroProject = arrText
    },
    reportViewClick() {
      const { state } = this.$store
      const { href } = this.$router.resolve({
        name: 'ConsultationReportView',
        path: '/detail/preview',
        query: {
          orderId: this.orders.id,
          authorization: this.$store.state.authorization,
          userId: state.user.id,
          consultationDetailId: this.opinionTabActive
        }
      })
      window.open(href, '_blank')
    },
    // 诊断模板 - 标签页点击
    diagnosisTemplateTabChange() {
      this.diagnosisTemplateRequest()
    },
    // 诊断模板 - 获取诊断模板
    async diagnosisTemplateRequest() {
      this.isDiagnosisTemplateReady = false
      const param = {
        type: this.diagnosisTemplatesType,
        key: this.diagnosisTemplateFilterKey
      }

      const res = await this.$axios({
        method: 'get',
        url: '/diagnose-templates',
        params: param
      })
      if (res && res.data.code === 200) {
        this.diagnosisTemplateList = []
        res.data.data.forEach(e => {
          this.diagnosisTemplateList.push({
            id: e.id,
            nodeName: e.nodeName,
            isLeaf: e.isLeaf,
            children: []
          })
        })
      } else {
        this.$message.info('请求失败')
      }
      this.isDiagnosisTemplateReady = true
    },
    async diagnosisTemplateFilter() {
      if (this.diagnosisTemplateFilterKey === '') {
        this.diagnosisTemplateRequest()
        return
      }

      this.isDiagnosisTemplateReady = false
      const param = {
        type: this.diagnosisTemplatesType,
        key: this.diagnosisTemplateFilterKey
      }

      const res = await this.$axios({
        method: 'get',
        url: '/diagnose-templates',
        params: param
      })

      if (res && res.data.code === 200) {
        // 确定默认展开节点
        this.diagnosisExpandList = []

        const firstNode = res.data.data[0]
        this.diagnosisExpandList.push(firstNode.id)
        if (_.get(firstNode, 'children.length', 0)) {
          const secondNode = firstNode.children[0]
          this.diagnosisExpandList.push(secondNode.id)
          if (_.get(secondNode, 'children.length', 0)) {
            const thirdNode = secondNode.children[0]
            this.diagnosisExpandList.push(thirdNode.id)
          }
        }
        // 确定树的数据
        this.diagnosisTemplateList = []
        res.data.data.forEach(e => {
          this.diagnosisTemplateList.push(e)
        })
        this.isDiagnosisTemplateReady = true
      } else {
        this.$message.info('请求失败')
        this.isDiagnosisTemplateReady = true
      }
    },
    // 诊断模板 - 节点加载
    async diagnosisTemplateLoad(node, resolve) {
      // 无效 id
      if (!node.data.id) {
        resolve([])
      } else if (this.diagnosisTemplateFilterKey === '') {
        const res = await this.$axios({
          method: 'GET',
          url: `/diagnose-templates/${node.data.id}`
        })
        if (res && res.data.code === 200) {
          resolve(res.data.data)
        }
      } else {
        // 叶子节点
        if (node.level >= 3) resolve([])
        if (node.data.parentId === 0) {
          // 根节点 - 展开
          this.diagnosisTemplateList.forEach(rootNode => {
            if (rootNode.id === node.data.id) {
              const results = rootNode.children
              resolve(results)
            }
          })
        } else {
          // 中间节点 - 展开
          this.diagnosisTemplateList.forEach(rootNode => {
            if (rootNode.children) {
              rootNode.children.forEach(secondLevel => {
                if (secondLevel.id === node.data.id) {
                  const results = secondLevel.children
                  resolve(results)
                }
              })
            }
          })
        }
      }
    },
    // 诊断模板 - 节点点击
    diagnosisTemplateNodeClick(data, node) {
      if (this.isMyOpinionTab && data.isLeaf) {
        if (this.opinionCurrent.input_binglizhenduan) {
          this.opinionCurrent.input_binglizhenduan += '\n'
          this.opinionCurrent.input_binglizhenduan += node.data.diagnoseLook
        } else {
          this.opinionCurrent.input_binglizhenduan = node.data.diagnoseLook
        }
        if (this.opinionCurrent.input_jujian) {
          this.opinionCurrent.input_jujian += '\n'
          this.opinionCurrent.input_jujian += node.data.diagnoseLook
        } else {
          this.opinionCurrent.input_jujian = node.data.diagnoseLook
        }
      }
    },
    // 诊断模板 - 节点复制
    async diagnosisTemplateNodeCopy(node) {
      const res = await this.$axios({
        method: 'POST',
        url: `/diagnose-templates/copy?id=${node.data.id}`
      })

      if (res && res.data.code === 200) {
        this.$message.success('复制成功')
      } else {
        this.$message.warning('复制失败')
      }
    },
    opinionTabListInit() {
      let _this = this
      const opinionList = _this.orders.patients[0].expertDiagnosis
      const doctorNotDiagnosis = opinionList.some(
        item => item.isFinal == 0 && (item.isFinished == null || item.isFinished == 0)
      )
      const finalDoctorStatus = opinionList.some(item => item.isFinal == 1 && item.type == 2)
      if (finalDoctorStatus) {
        this.isThereAFinalReview = 1
      } else {
        this.isThereAFinalReview = 0
      }

      if (doctorNotDiagnosis) {
        opinionList.forEach(t => {
          if (t.isFinal == 0) {
            _this.opinionTabList.push({
              key: t.id.toString(),
              expertId: t.expertId,
              label:
                t.isFinal == 1
                  ? t.expertName +
                    '(终审)' +
                    t.createTime +
                    (t.isFinished == 1 ? '已发布' : '未发布')
                  : t.type == 1
                  ? t.expertName +
                    '(邀请)' +
                    t.createTime +
                    (t.isFinished == 1 ? '已发布' : '未发布')
                  : t.expertName +
                    '(诊断)' +
                    t.createTime +
                    (t.isFinished == 1 ? '已发布' : '未发布')
            })
          }
        })
      } else {
        opinionList.forEach(t => {
          _this.opinionTabList.push({
            key: t.id.toString(),
            expertId: t.expertId,
            label:
              t.isFinal == 1
                ? t.expertName + '(终审)' + t.createTime + (t.isFinished == 1 ? '已发布' : '未发布')
                : t.type == 1
                ? t.expertName + '(邀请)' + t.createTime + (t.isFinished == 1 ? '已发布' : '未发布')
                : t.expertName + '(诊断)' + t.createTime + (t.isFinished == 1 ? '已发布' : '未发布')
          })
        })
      }

      let primaryOpinion = _this.opinionTabList.find(t => t.expertId == _this.user.id)
      if (_this.opinionTabList) {
        if (!primaryOpinion) {
          primaryOpinion = _this.opinionTabList[0]
        }
        _this.opinionTabActive = primaryOpinion.key
      }
      _this.opinionDataInit()

      //setOptionCurrent
      _this.setOptionCurrent(_this.opinionTabActive)
    },
    getOpinionBySpecialistId(id) {
      // const currentButInfo = this.opinionList.find(t => t.id == Number(id))
      // this.opinionList.forEach((item, index) => {
      //   if (currentButInfo.expertId == item.expertId && item.detailString) {
      //     currentButInfo.detailString = item.detailString
      //   }
      // })
      // return currentButInfo
      return this.opinionList.find(t => t.id == Number(id))
    },
    // 意见 - 查看他人时，保存表单数据到缓存，加载缓存数据到表单
    opinionTabChange(activeTab) {
      const _this = this
      _this.setOptionCurrent(Number(activeTab.name))
    },

    setOptionCurrent(id) {
      const _this = this
      _this.opinionTabActiveId = id.toString()
      const opinion = _this.getOpinionBySpecialistId(id)
      _this.tabActiveUserId = opinion.expertId
      _this.opinionCurrent =
        opinion.detailString != null
          ? JSON.parse(_.get(opinion, 'detailString', {}))
          : {
              input_binglizhenduan: '',
              input_jujian: '',
              input_extroProject: ''
            }
    },
    opinionDataInit() {
      const id = parseInt(this.opinionTabActive, 10)
      this.setOptionCurrent(id)
    },
    // 复制
    async copyClick() {
      // console.log(this.opinionTabList)
      // console.log(this.opinionList?.find(n => n.expertId === this.user.id && n.isFinished !== 1))
      // return
      debugger
      const tId =
        this.opinionList?.find(n => n.expertId === this.user.id && n.isFinished !== 1)?.id || ''

      const rId = this.opinionTabList?.find(n => n.expertId === this.tabActiveUserId)?.key || ''
      if (!tId || !rId) {
        return
      }
      this.$confirm('此操作将复制他人诊断报告，删除您的诊断报告, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await this.$axios({
          url: '/diagnosis_data/duplicate/' + rId + '/' + tId,
          method: 'get'
        })
        if (res.data.code == 200) {
          if (res.data.data === true) {
            this.$message({
              type: 'success',
              message: '复制成功!'
            })
            this.$emit('consultationRequest')
          }
        }
      })

      // if (res && res.data.code === 200) {
      //   this.$message.success('保存成功')
      //   const opinion = _this.getOpinionBySpecialistId(_this.thisOpinion.id)
      //   opinion.detailString = JSON.stringify(_this.opinionCurrent)
      // } else {
      //   this.$message.error('保存失败')
      // }
    },
    // 会诊 - 保存
    async consultationSave() {
      let _this = this
      const res = await this.$axios({
        url: '/consultationsDetail',
        method: 'POST',
        data: {
          id: _this.thisOpinion.consultationDetailId,
          expertDiagnosisId: _this.thisOpinion.id,
          detailString: JSON.stringify(_this.opinionCurrent)
        }
      })

      if (res && res.data.code === 200) {
        this.$message.success('保存成功')
        const opinion = _this.getOpinionBySpecialistId(_this.thisOpinion.id)
        opinion.detailString = JSON.stringify(_this.opinionCurrent)
      } else {
        this.$message.error('保存失败')
      }
    },
    // 会诊 - 发布
    async consultationIssue() {
      let _this = this
      const detailString = JSON.stringify(this.opinionCurrent)
      const res = await _this.$axios({
        url: `/consultations/${this.thisOpinion.id}/${this.isThereAFinalReview}/issue`,
        method: 'PUT',
        data: {
          detailString
        }
      })

      if (res && res.data.code === 200) {
        _this.$message.success('发布成功')
        _this.$emit('consultationRequest')
      } else {
        _this.$message.error('发布失败')
      }
    },
    // 会诊 - 退回
    consultationSendBack() {
      this.$prompt('请输入退回说明', '退回说明', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /.*[^\s]/,
        inputErrorMessage: '退回说明不能为空'
      })
        .then(async ({ value }) => {
          const res = await this.$axios({
            method: 'PUT',
            url: `/consultations/${this.uArgs.consultationId}/send-back`,
            params: {
              remark: value
            }
          })

          if (res && res.data.code === 200) {
            this.$message.success('退回成功')
            this.$router.go(-1)
          } else {
            this.$message.warning('退回失败')
          }
        })
        .catch(() => {
          this.$message.info('取消操作')
        })
    },
    // 会诊 - 回收
    consultationRecycle() {
      this.$prompt('请输入回收说明', '回收说明', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /.*[^\s]/,
        inputErrorMessage: '回收说明不能为空'
      })
        .then(async ({ value }) => {
          const res = await this.$axios({
            method: 'GET',
            url: `/expert/diagnosis/callback/${this.primaryOpinion.id}`,
            params: {
              remark: value
            }
          })

          if (res && res.data.code === 200) {
            this.$message.success('回收成功')
            this.$emit('consultationRequest')
          } else {
            this.$message.warning('回收失败')
          }
        })
        .catch(() => {
          this.$message.info('取消操作')
        })
    },
    goBack() {
      this.$router.go(-1)
    },
    inviteDialogOpen() {
      this.inviteTableDataRequest()
      this.inviteDialog.visible = true
    },
    inviteTablePageJumpTo(val) {
      this.inviteTable.pageInfo.page = val
      this.inviteTableDataRequest()
    },
    inviteTableSizeChange(val) {
      this.inviteTable.pageInfo.size = val
      this.inviteTableDataRequest()
    },
    inviteTableSelectedRow(selectedRow) {
      this.inviteSelected = _.clone(selectedRow)
    },
    inviteTableDataRequest() {
      this.inviteTable.isReady = false
      try {
        this.$axios({
          method: 'GET',
          url: `/consultations/${this.orders.serviceCenterId}/${this.orders.patients[0].id}/invitation-experts`,
          params: {
            page: this.inviteTable.pageInfo.page - 1,
            size: this.inviteTable.pageInfo.size
          }
        }).then(res => {
          if (res && res.data.code === 200) {
            // 分页处理
            this.inviteTable.pageInfo = {
              total: res.data.pageInfo.total,
              page: res.data.pageInfo.page + 1,
              size: res.data.pageInfo.size
            }
            // 数据处理
            this.inviteTable.data = []
            if (res.data.data) {
              res.data.data.forEach((t, index) => {
                const user = {
                  index,
                  id: t.id,

                  name: t.name,
                  genderName: t.genderName,
                  jobNumber: t.jobNumber,
                  positionName: t.positionName,
                  medicalTitleName: t.medicalTitleName,
                  createTime: moment(t.createTime).format('YYYY-MM-DD'),
                  statusName: t.status ? '冻结' : '正常',
                  area: t.area,
                  idCardStatusName: '',
                  qualityStatusName: '',

                  roleList: t.roles,
                  status: t.status
                }

                this.inviteTable.data.push(user)
              })
            }
          }

          this.inviteTable.isReady = true
        })
      } catch (e) {
        this.inviteTable.isReady = true
        this.$message.warning('请求失败')
      }
    },
    async inviteSpecialist() {
      const expertIdArr = []
      this.inviteSelected.forEach(index => {
        expertIdArr.push(this.inviteTable.data[index].id)
      })
      const res = await this.$axios({
        method: 'PUT',
        url: `/consultations/${this.orders.patients[0].id}/invite`,
        params: {
          expertIdArr
        },
        paramsSerializer(params) {
          return Qs.stringify(params, { arrayFormat: 'repeat' })
        }
      })

      if (res && res.data.code === 200) {
        this.$message.success('邀请成功')
        this.$emit('consultationRequest')
        this.inviteDialog.visible = false
      } else {
        this.$message.warning('邀请失败')
      }
    },
    addStaining() {
      this.$refs.consultationPlus.addDyeingHandelClick()
    },
    addMolecular() {
      this.$refs.consultationPlus.addMolecularHandelClick()
    },
    addInc() {
      this.$refs.consultationPlus.addIncHandelClick()
    }
  }
}
</script>

<style scoped>
.diagnosis-template-tree {
  flex: 1;

  display: flex;

  align-items: center;

  justify-content: space-between;
}
.diagnosis-template-tree-message {
  font-size: 14px;

  width: 100%;

  overflow: hidden;

  white-space: nowrap;

  text-overflow: ellipsis;
}
.qrcode-box {
  padding: 20px;
  margin: 20px auto;
  border-top: 1px solid #dcdcdc;
  display: flex;
  justify-content: space-around;
}
</style>
